<?php

namespace app\order\logic;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class OrderunfulfilledLogic
{
    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $order_id = $params['order_id'] ?? 0;
        $shop_id = $params['shop_id'] ?? 0;
        $createtime = $params['createtime'] ?? "";
        $payout_status = $params['payout_status'] ?? "";

        $where = [];

        if (!empty($createtime)) {
            $where[] = ['createtime', '>=', strtotime($createtime['0'])];
            $where[] = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }
        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }
        if(!empty($order_id)){
            $where[] = ['order_id','like', '%'.$order_id.'%'];
        }

        $where[] = ['fulfillment_status', '=', ""];
        $where[] = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded"]];

        if(!empty($payout_status)){
            $list = $this->payout_status($params);
        }else{
            $list = Db::name('order_achievement')
                ->field('
                    id,order_id,shop_id,payment_gateway_names,financial_status,
                    currency,
                    total_price,
                    createtime,sku,spu
                ')
                ->where($where)
                ->order('createtime desc')
                ->paginate($limit);
        }
        
        $lists = $list->items();

        $spu_map = [];
        foreach ($lists as $k=>$v) {
            $pos = strpos($v['spu'], ',');
            if($pos !== false){
                $spus = explode(',',$v['spu']);
                foreach ($spus as $key=>$value) {
                    $spu_map[$value] = 1;
                }
            }else{
                $spu_map[$v['spu']] = 1;
            }
        }
        $spus = array_keys($spu_map);
        
        //店铺
        $shop_ids = array_column($lists,'shop_id');
        $shop_ids = array_values(array_unique($shop_ids));
        $shop_info= Db::name('shops')->field('id,name')->whereIn('id',$shop_ids)->select();
        $shop_info= objectToArray($shop_info);
        $shop_info_map = array_column($shop_info,null,'id');

        //批量获取图片地址;
        $products     = Db::name('product_inventory')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');
        $product_names= Db::name('product')->field('spu,product_name,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_name_map = array_column($product_names,null,'spu');

        foreach ($lists as &$v) {
            
            $product_images_inquiry    = $products_map[$v['spu']]??[];
            $product_images_product    = $products_name_map[$v['spu']]??[];
            $product_name              = $product_images_product['product_name']??'';
            if(!$product_name)           $product_name = '女士内衣';
            $v['product_name'] = $product_name;
            $product_images            = $product_images_product['product_images']??[];
            $display_images            = $product_images ? current(json_decode($product_images)) : '';
            if(!$display_images) {
                $display_images        = $product_images_inquiry['product_images']??'';
            }
            $v['product_images'] = $display_images;

            $v['createtime'] = date('Y-m-d H:i',$v['createtime']);

            $shop_infos = $shop_info_map[$v['shop_id']]??[];
            $v['shop_name'] = $shop_infos['name']??'';

            $v['sku'] = explode(',',$v['sku']);
        }

        $UnshippedDays[0]['name'] = '7天未发货';
        //48小时未发货
        $where_time = [];
        $where_time[] = ['createtime', '>=', time()-timezone()-24*3600*7];
        $count = Db::name('order_achievement')
            ->where($where)
            ->where($where_time)
            ->count();
        $UnshippedDays[0]['count'] = $count;

        $UnshippedDays[1]['name'] = '15天未发货';
        $where_time = [];
        $where_time[] = ['createtime', '>=', time()-timezone()-24*3600*15];
        $count = Db::name('order_achievement')
            ->where($where)
            ->where($where_time)
            ->count();
        $UnshippedDays[1]['count'] = $count;

        $UnshippedDays[2]['name'] = '30天未发货';
        $where_time = [];
        $where_time[] = ['createtime', '>=', time()-timezone()-24*3600*30];
        $count = Db::name('order_achievement')
            ->where($where)
            ->where($where_time)
            ->count();
        $UnshippedDays[2]['count'] = $count;

        $UnshippedDays[3]['name'] = '所有未发货';
        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        $UnshippedDays[3]['count'] = $count;

        $data = [
            'list' => $lists,
            'total' => $list->total(),
            'spends' => [],
            'spends_Total' => [],
            'UnshippedDays' => $UnshippedDays,
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }


    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function payout_status($params)
    {
        $limit = $params['limit'] ?? 10;
        $order_id = $params['order_id'] ?? 0;
        $shop_id = $params['shop_id'] ?? 0;
        $createtime = $params['createtime'] ?? "";
        $payout_status = $params['payout_status'] ?? "";

        $where = [];
        if (!empty($createtime)) {
            $where[] = ['a.createtime', '>=', strtotime($createtime['0'])];
            $where[] = ['a.createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }
        if(!empty($shop_id)){
            $where[] = ['a.shop_id', '=', $shop_id];
        }
        if(!empty($order_id)){
            $where[] = ['a.order_id','like', '%'.$order_id.'%'];
        }
        $where[] = ['a.fulfillment_status', '=', ""];
        $where[] = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded"]];
        
        switch ($payout_status) {
            case 'OutOfStock':
                $list = Db::name('order_achievement')
                    ->field('
                        a.id,a.order_id,a.shop_id,a.payment_gateway_names,a.financial_status,
                        a.currency,
                        a.total_price,
                        a.createtime,a.sku,a.spu
                    ')
                    ->alias('a')
                    ->join('order_info b','b.order_id = a.order_id', 'left')
                    ->join('product_inventory c','c.seller_sku = b.sku', 'left')
                    ->where($where)
                    ->where("c.inventory_quantity",">=",1)
                    ->order('a.createtime desc')
                    ->paginate($limit);
                break;
            case 'InStock':
                $list = Db::name('order_achievement')
                    ->field('
                        a.id,a.order_id,a.shop_id,a.payment_gateway_names,a.financial_status,
                        a.currency,
                        a.total_price,
                        a.createtime,a.sku,a.spu
                    ')
                    ->alias('a')
                    ->join('order_info b','b.order_id = a.order_id', 'left')
                    ->join('product_inventory c','c.seller_sku = b.sku', 'left')
                    ->where($where)
                    ->where("c.inventory_quantity","<=",0)
                    ->order('a.createtime desc')
                    ->paginate($limit);
                break;
            default:
        }
        return $list;
    }
    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['类型', 'type'];
        $header[] = ['状态', 'payout_status'];
        $header[] = ['金额', 'amount'];
        $header[] = ['订单ID', 'source_order_id'];
        $header[] = ['交易时间', 'processed_at'];
        $header[] = ['订单时间', 'created_at'];

        $tableName = "Orderunfulfilled";

        $payout_status = $params['payout_status'] ?? "";
        $shop_id = $params['shop_id'] ?? 0;
        $createtime = $params['createtime'] ?? "";
        $processed_at = $params['processed_at'] ?? "";
        $source_order_id = $params['source_order_id'] ?? 0;

        $where = [];

        if (!empty($createtime)) {
            $where[] = ['createtime', '>=', strtotime($createtime['0'])];
            $where[] = ['createtime', '<=', strtotime($createtime['1']) + 3600*24-1];
        }
        if (!empty($processed_at)) {
            $where[] = ['processed_at', '>=', $processed_at['0']];
            $where[] = ['processed_at', '<=', date('Y-m-d',strtotime($processed_at['1']) + 3600*24)];
        }
        
        if(!empty($shop_id)){
            $where[] = ['shop_id', '=', $shop_id];
        }
        if(!empty($payout_status)){
            $where[] = ['payout_status', '=', $payout_status];
        }
        if(!empty($source_order_id)){
            $where[] = ['source_order_id', 'like', '%' . $source_order_id . '%'];
        }

        $count = Db::name('order_balance_api')
            ->where($where)
            ->count();
        if($count >= 5000){
            return '数据超过5000条,异步下载中，请2分钟后前往【任务组管理/系统导出管理】页面下载';
        }

        $lists = Db::name('order_balance_api')
            ->where($where)
            ->order('processed_at desc')
            ->select()->toarray();

        foreach ($lists as &$v) {
            $v['source_order_id'] = '订单ID:'.$v['source_order_id'];
        }
        
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

}
